package com.jun.admin.core.model.strategy;

import com.jun.common.core.exception.ServiceException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author yuejun.li
 * @date 2024/6/25 10:11:14
 */
@Component
public class PaymentStrategyFactory implements InitializingBean {

    @Autowired
    private ApplicationContext applicationContext;

    private static final Map<String, PaymentStrategy> paymentMap = new HashMap<>();

    /**
     * 根据枚举来获取购物策略
     * @param paymentStyle
     * @return
     */
    public PaymentStrategy doOperate(String paymentStyle) {
        if (Objects.isNull(paymentStyle)) {
            throw new ServiceException("请输入正确的枚举");
        }
        return paymentMap.get(paymentStyle);
    }

    /**
     * Spring启动时将所有处理类加载好由Spring管理
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        //根据抽象接口获取所有子实现类
        Map<String, PaymentStrategy> beansOfType = applicationContext.getBeansOfType(PaymentStrategy.class);
        for (Map.Entry<String, PaymentStrategy> entry : beansOfType.entrySet()) {
            paymentMap.put(entry.getKey(),entry.getValue());
        }
    }
}
